package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.store.ibatis.IDeparmentBasicDao;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.FuAssessMentPosition;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.entity.PatientTaskContent;
import com.bbcare.followup.plat.service.IAppUserService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IFamilyReportDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowEvaluationDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;

/**
 * @name: app端调用随访系统服务类接口实现
 * @author: DemonLee
 * @createTime: 2017.5.19
 * @description: 随访系统提供给app端调用的相关服务接口实现
 * @modify:
 *
 */
@Service
public class AppUserService implements IAppUserService {
    private final Log logger = LogFactory.getLog(AppUserService.class);

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private IFollowQueueDAO queueDao;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IContentTemplDAO contentTemplDao;

    @Autowired
    private IPatientTaskDAO patientTaskDao;

    @Autowired
    private IPatientTaskContentDAO patientTaskConDao;

    @Autowired
    public IConfCacheDAO confCacheDao;

    @Autowired
    private IPatientService patientSerivce;

    @Autowired
    private IDeparmentBasicDao departBasicDao;

    @Autowired
    IFollowEvaluationDAO followEvaluationDao;

    @Autowired
    IFamilyReportDAO familyReportDao;

    // @Autowired
    // private IConfCacheRedis confCacheRedis;

    @Resource(name = "jedisPool")
    private JedisPool jedisPool;

    // 通用接口，查询线上主诉登记、线上随访的任务内容实现
    public HashMap<String, Object> getOnlinePtTaskContDataInfo(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String patientId = (String) argMap.get("patientId");
        String queueId = (String) argMap.get("queueId");
        String type = (String) argMap.get("type");
        String taskType = "";
        if ("8".equals(type)) {
            taskType = Constants.TASK_TYPE_NONSCHEME_REALTIME;// 主诉登记
        } else {
            taskType = Constants.TASK_TYPE_SCHEME_TEMP;// 线上随访
        }

        // 校验患者信息是否存在
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", patientId);
        userMapIn.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userMapIn);
        if (null == ptVo || "".equals(ptVo.getId())) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
        }

        HashMap<String, Object> quMap = new HashMap<String, Object>();
        quMap.put("userId", patientId);
        quMap.put("queueId", queueId);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(quMap);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "队列实例表中无此患者信息！");
        }
        PatientQueueScheme psVo = pqsList.get(0);
        String userStatus = psVo.getUserStatus();
        if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL,
                    "患者在该队列中状态异常，无法进行相关操作！");
        }

        String taskId = "";
        HashMap<String, Object> taskInMap = new HashMap<String, Object>();
        taskInMap.put("ptSchemeId", psVo.getId());
        if (Constants.TASK_TYPE_SCHEME_TEMP.equals(taskType)) {
            taskInMap.put("endTime", DateUtil.getCurrDate());
            taskInMap.put("beginTime", DateUtil.getCurrDate());
            taskInMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);
        }
        taskInMap.put("revSeqNo", 0);// 去掉建档任务
        taskInMap.put("taskType", taskType);
        List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
        if (CollectionUtils.isEmpty(ptVoList)) {
            return retOutMap;
        }
        PatientTask ptTaskVo = ptVoList.get(0);
        taskId = ptTaskVo.getId();
        String ruleType = ptTaskVo.getRuleType();
        if (StringUtils.isEmpty(ruleType)) {
            ruleType = "";
        }

        taskInMap.clear();
        taskInMap.put("taskId", taskId);
        if (Constants.TASK_TYPE_SCHEME_SELFREPORT_COMMON.equals(ruleType)) {
            // 通用主诉登记
        } else if (Constants.TASK_TYPE_SCHEME_SELFREPORT_MONTHAGE.equals(ruleType)) {
            // 纠正月龄主诉登记
            taskInMap.put("endDate", DateUtil.getCurrDate());
            taskInMap.put("beginDate", DateUtil.getCurrDate());
        }
        // taskInMap.put("contTemplType", type);// 问卷模板类型
        List<Object> conDataList = new ArrayList<Object>();
        List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
        if (!CollectionUtils.isEmpty(ptcList)) {
            // questiones
            int ipt = 0;
            int isize = ptcList.size();
            Map<String, Object> dataOut = new HashMap<String, Object>();
            Map<String, Object> contVerMap = new HashMap<String, Object>();
            for (ipt = 0; ipt < isize; ipt++) {
                PatientTaskContent ptaskc = ptcList.get(ipt);
                // 获取内容模板
                contVerMap.clear();
                contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
                dataOut = patientSerivce.getContTemplData(contVerMap);
                if (null != dataOut.get("contData")) {
                    conDataList.add(dataOut.get("contData"));
                }
            }
            retOutMap.put("questiones", conDataList);

            // values:上次填写的答案
            HashMap<String, Object> valuesMap = new HashMap<String, Object>();
            Map<String, Object> valMapIn = new HashMap<String, Object>();
            valMapIn.put("taskId", taskId);
            // valMapIn.put("contDataTemplType", type);
            if (Constants.TASK_TYPE_SCHEME_SELFREPORT_COMMON.equals(ruleType)) {
                // 通用主诉登记（今天填写的记录）
                valMapIn.put("opTime", DateUtil.getCurrDate());
            } else if (Constants.TASK_TYPE_SCHEME_SELFREPORT_MONTHAGE.equals(ruleType)) {
                // 纠正月龄主诉登记（待完善）
            }
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                int k = 0;
                for (; k < ptTaskConList.size(); k++) {
                    PatientContentData pcdVo = ptTaskConList.get(k);
                    valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                }
            }
            retOutMap.put("values", valuesMap);
        } else {
            return retOutMap;
        }

        // task
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("ptTaskId", taskId);
        taskMap.put("ptTaskName", ptTaskVo.getTaskName());
        taskMap.put("seqNo", ptTaskVo.getSeqNo());
        taskMap.put("type", type);
        retOutMap.put("taskInfo", taskMap);

        // ptQueue
        HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
        oprInfoMap.put("patientId", ptTaskVo.getUserId());
        oprInfoMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
        oprInfoMap.put("followQueueId", queueId);
        retOutMap.put("ptQueueInfo", oprInfoMap);
        return retOutMap;
    }

    // 患者任务内容列表查询接口实现
    public HashMap<String, Object> getAppPtTaskContDataInfo(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String patientId = (String) argMap.get("patientId");
        String queueId = (String) argMap.get("queueId");
        String type = (String) argMap.get("type");
        String custValType = (String) argMap.get("custValType");// 客户标识，安医大特殊处理

        // 校验患者信息是否存在
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", patientId);
        userMapIn.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userMapIn);
        if (null == ptVo || "".equals(ptVo.getId())) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
        }

        HashMap<String, Object> quMap = new HashMap<String, Object>();
        quMap.put("userId", patientId);
        quMap.put("queueId", queueId);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(quMap);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "队列实例表中无此患者信息！");
        }
        PatientQueueScheme psVo = pqsList.get(0);
        String userStatus = psVo.getUserStatus();
        if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL,
                    "患者在该队列中状态异常，无法进行相关操作！");
        }

        String taskId = "";
        HashMap<String, Object> taskInMap = new HashMap<String, Object>();
        taskInMap.put("ptSchemeId", psVo.getId());
        taskInMap.put("endTime", DateUtil.getCurrDate());
        taskInMap.put("beginTime", DateUtil.getCurrDate());
        taskInMap.put("revSeqNo", 0);// 去掉建档任务
        taskInMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
        List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
        if (CollectionUtils.isEmpty(ptVoList)) {
            if (!StringUtils.isEmpty(custValType)) {
                // 若没有当前窗口期的任务，则用第一次随访任务替代(针对安医大项目)
                taskInMap.clear();
                taskInMap.put("ptSchemeId", psVo.getId());
                taskInMap.put("seqNo", 1);
                taskInMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
                ptVoList = patientTaskDao.select(taskInMap);
                if (CollectionUtils.isEmpty(ptVoList)) {
                    // throw new
                    // AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TASK_NOT_EXIST,
                    // "该患者无任务信息！");
                    return retOutMap;
                }
            } else {
                return retOutMap;
            }
        }
        PatientTask ptTaskVo = ptVoList.get(0);
        taskId = ptTaskVo.getId();

        taskInMap.clear();
        taskInMap.put("taskId", taskId);
        taskInMap.put("contTemplType", type);// 问卷模板类型
        List<Object> conDataList = new ArrayList<Object>();
        List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
        if (!CollectionUtils.isEmpty(ptcList)) {
            // questiones
            int ipt = 0;
            int isize = ptcList.size();
            Map<String, Object> dataOut = new HashMap<String, Object>();
            Map<String, Object> contVerMap = new HashMap<String, Object>();
            for (ipt = 0; ipt < isize; ipt++) {
                PatientTaskContent ptaskc = ptcList.get(ipt);
                // System.out.println("11111111111111111111");
                // 获取内容模板
                contVerMap.clear();
                contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
                dataOut = patientSerivce.getContTemplData(contVerMap);
                if (null != dataOut.get("contData")) {
                    // System.out.println("222222222222222222");
                    conDataList.add(dataOut.get("contData"));
                }
            }
            retOutMap.put("questiones", conDataList);

            // values:上次填写的答案
            HashMap<String, Object> valuesMap = new HashMap<String, Object>();
            Map<String, Object> valMapIn = new HashMap<String, Object>();
            valMapIn.put("taskId", taskId);
            valMapIn.put("contDataTemplType", type);
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                int k = 0;
                for (; k < ptTaskConList.size(); k++) {
                    PatientContentData pcdVo = ptTaskConList.get(k);
                    valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                }
            }
            retOutMap.put("values", valuesMap);
        }

        // task
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("ptTaskId", taskId);
        taskMap.put("ptTaskName", ptTaskVo.getTaskName());
        taskMap.put("seqNo", ptTaskVo.getSeqNo());
        taskMap.put("type", type);
        retOutMap.put("taskInfo", taskMap);

        // ptQueue
        HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
        oprInfoMap.put("patientId", ptTaskVo.getUserId());
        oprInfoMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
        oprInfoMap.put("followQueueId", queueId);
        retOutMap.put("ptQueueInfo", oprInfoMap);
        // System.out.println("4444444444444444444");
        return retOutMap;
    }

    // 根据患者id查询加入的队列list接口实现
    public Map<String, Object> listPtQueueInfo(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> argMap = new HashMap<String, Object>(paramMap);
        Map<String, Object> retOutMap = new HashMap<String, Object>();
        List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();

        // 校验患者信息是否存在
        String patientId = (String) argMap.get("patientId");
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", patientId);
        userMapIn.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userMapIn);
        if (null == ptVo || "".equals(ptVo.getId())) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
        }

        // 找到app科室id对应的随访科室id
        String followDeptId = "";
        String appDeptId = (String) argMap.get("departmentId");
        if (!StringUtils.isEmpty(appDeptId)) {
            Map<String, Object> deptBasicMap = new HashMap<String, Object>();
            deptBasicMap.put("refDeptId", appDeptId);
            List<DepartmentBasic> deptList = departBasicDao.selectByRefDeptId(deptBasicMap);
            if (CollectionUtils.isEmpty(deptList)) {
                // throw new
                // AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST,
                // "未查询到关联科室id！");
                logger.error("未查询到关联科室id！");
                return retOutMap;// 老随访数据未刷，这里为了友好展示，直接返回空给app端
            }
            followDeptId = deptList.get(0).getId();
        }

        List<String> queueIdList = new ArrayList<String>();
        if (!StringUtils.isEmpty(followDeptId)) {
            if (!StringUtils.isEmpty(followDeptId)) {
                // 根据科室id查询该科室下的队列id
                Map<String, Object> queueMapIn = new HashMap<String, Object>();
                queueMapIn.put("deptId", followDeptId);
                List<FollowQueue> queueList = queueDao.selectByDeptId(queueMapIn);
                if (CollectionUtils.isEmpty(queueList)) {
                    // throw new
                    // AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST,
                    // "该科室id下未配置队列！");
                    logger.error("该科室id下未配置队列！");
                    return retOutMap;// 老随访数据未刷，这里为了友好展示，直接返回空给app端
                }
                FollowQueue fqVo = new FollowQueue();
                int qsize = queueList.size();
                int k = 0;
                for (k = 0; k < qsize; k++) {
                    // 判断队列状态是否正常
                    fqVo = queueList.get(k);
                    if (Constants.QUEUE_STATUS_NOMAL.equals(fqVo.getQueueStatus())) {
                        queueIdList.add(fqVo.getId());
                    }
                }
            }
        }
        if (0 != queueIdList.size()) {
            userMapIn.put("queueIdIn", queueIdList);
        }

        // 查询该患者加入的队列
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(userMapIn);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "该患者未加入任何队列！");
        }
        int kp = 0;
        int lsize = pqsList.size();
        PatientQueueScheme pqsVo = new PatientQueueScheme();
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(Constants.REDIS_DB_INDEX_CONFIG);

            Map<String, Object> qryMapIn = new HashMap<String, Object>();
            Map<String, Object> qryMapOut = new HashMap<String, Object>();
            for (kp = 0; kp < lsize; kp++) {
                Map<String, Object> ptQueueMap = new HashMap<String, Object>();
                pqsVo = pqsList.get(kp);
                String userStatus = pqsVo.getUserStatus();
                if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
                    continue;
                }

                ptQueueMap.put("ptSchemeId", pqsVo.getId());
                ptQueueMap.put("taskTotalNum", pqsVo.getTotalNum());
                ptQueueMap.put("taskFinishNum", pqsVo.getFinishNum());
                ptQueueMap.put("taskLostNum", pqsVo.getLostNum());
                ptQueueMap.put("cardNo", pqsVo.getCardNo());
                ptQueueMap.put("cardStatus", pqsVo.getCardStatus());
                ptQueueMap.put("cardType", pqsVo.getCardType());
                ptQueueMap.put("userStatus", pqsVo.getUserStatus());
                ptQueueMap.put("hisNo1", pqsVo.getHisNo1());
                ptQueueMap.put("hisNo2", pqsVo.getHisNo2());
                ptQueueMap.put("hisNo3", pqsVo.getHisNo3());
                ptQueueMap.put("schemeId", pqsVo.getSchemeId());
                ptQueueMap.put("queueId", pqsVo.getQueueId());

                qryMapIn.clear();
                qryMapIn.put("queueId", pqsVo.getQueueId());
                qryMapIn.put("schemeId", pqsVo.getSchemeId());
                // 获取队列名称
                qryMapOut = patientSerivce.getQueueName(qryMapIn, jedis);
                ptQueueMap.put("queueName", qryMapOut.get("queueName"));
                // 获取方案名称
                qryMapOut = patientSerivce.getSchemeName(qryMapIn, jedis);
                ptQueueMap.put("schemeName", qryMapOut.get("schemeName"));

                retList.add(ptQueueMap);
            }
        } catch (JedisConnectionException jex) {
            logger.error("redis连接异常..." + jex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
        } finally {
            if (null != jedis) {
                try {
                    jedis.close();
                    logger.warn("close redis connection...");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
                            "Redis缓存关闭失败!"));
                }
            }
        }

        retOutMap.put("total", retList.size());
        retOutMap.put("rows", retList);

        return retOutMap;
    }

    // 患者是否存在线上随访问卷(查询窗口期内的线上问卷)接口实现
    public HashMap<String, Object> getPtOnlineTaskInform(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String patientId = (String) argMap.get("patientId");
        String appDeptId = (String) argMap.get("departmentId");
        String queueId = (String) argMap.get("queueId");
        String type = (String) argMap.get("type");
        String taskType = Constants.TASK_TYPE_SCHEME_TEMP;// 默认线上随访
        if ("1".equals(type)) {
            taskType = Constants.TASK_TYPE_SCHEME_TEMP;
        }

        // 校验患者信息是否存在
        Map<String, Object> userInMap = new HashMap<String, Object>();
        userInMap.put("userId", patientId);
        userInMap.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userInMap);
        if (null == ptVo || StringUtils.isEmpty(ptVo.getId())) {
            logger.error("随访系统无此患者【" + patientId + "】信息！");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "随访系统无此患者信息！");
        }

        // 找到app科室id对应的随访科室id
        String followDeptId = "";
        if (!StringUtils.isEmpty(appDeptId)) {
            Map<String, Object> deptBasicMap = new HashMap<String, Object>();
            deptBasicMap.put("refDeptId", appDeptId);
            List<DepartmentBasic> deptList = departBasicDao.selectByRefDeptId(deptBasicMap);
            if (CollectionUtils.isEmpty(deptList)) {
                logger.error("根据【" + appDeptId + "】未查询到关联科室id！");
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到关联科室id！");
            }
            followDeptId = deptList.get(0).getId();
        }

        List<String> queueIdList = new ArrayList<String>();
        if (!StringUtils.isEmpty(followDeptId)) {
            // 根据科室id查询该科室下的队列id
            Map<String, Object> queueMapIn = new HashMap<String, Object>();
            queueMapIn.put("deptId", followDeptId);
            List<FollowQueue> queueList = queueDao.selectByDeptId(queueMapIn);
            if (CollectionUtils.isEmpty(queueList)) {
                logger.error("该科室id【" + followDeptId + "】下未配置队列！");
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "该科室id下未配置队列！");
            }
            FollowQueue fqVo = new FollowQueue();
            int qsize = queueList.size();
            int k = 0;
            for (k = 0; k < qsize; k++) {
                // 判断队列状态是否正常
                fqVo = queueList.get(k);
                if (Constants.QUEUE_STATUS_NOMAL.equals(fqVo.getQueueStatus())) {
                    queueIdList.add(fqVo.getId());
                }
            }
        } else {
            queueIdList.add(queueId);
        }
        if (CollectionUtils.isEmpty(queueIdList)) {
            return retOutMap;
        }

        Map<String, Object> quMap = new HashMap<String, Object>();
        quMap.put("userId", patientId);
        quMap.put("queueIdIn", queueIdList);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(quMap);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "该患者未加入相关队列！");
        }

        List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
        int ipqsize = pqsList.size();
        int t = 0;
        int totalNum = 0;// 问卷个数
        for (t = 0; t < ipqsize; t++) {
            PatientQueueScheme psVo = pqsList.get(t);
            String userStatus = psVo.getUserStatus();
            if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
                logger.warn("患者在该队列【" + psVo.getQueueId() + "】中状态异常，无法进行相关操作！");
                continue;
            }

            String taskId = "";
            // 查询窗口期内的任务
            HashMap<String, Object> taskInMap = new HashMap<String, Object>();
            taskInMap.put("ptSchemeId", psVo.getId());
            taskInMap.put("endTime", DateUtil.getCurrDate());
            taskInMap.put("beginTime", DateUtil.getCurrDate());
            taskInMap.put("revSeqNo", 0);// 去掉建档任务
            taskInMap.put("taskType", taskType);// 查询对应类型的随访任务
            taskInMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);
            List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
            if (CollectionUtils.isEmpty(ptVoList)) {
                continue;
            }
            PatientTask ptTaskVo = ptVoList.get(0);
            taskId = ptTaskVo.getId();

            taskInMap.clear();
            taskInMap.put("taskId", taskId);
            // taskInMap.put("contTemplType", type);// 问卷模板类型
            List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
            if (!CollectionUtils.isEmpty(ptcList)) {
                // values:上次填写的答案
                Map<String, Object> valMapIn = new HashMap<String, Object>();
                valMapIn.put("taskId", taskId);
                // valMapIn.put("contDataTemplType", type);
                List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
                if (!CollectionUtils.isEmpty(ptTaskConList)) {
                    // 已填写过问卷，过滤掉
                    continue;
                }

                PatientTaskContent ptcVo = ptcList.get(0);
                Map<String, Object> contVerMap = new HashMap<String, Object>();
                contVerMap.put("id", ptcVo.getTemplVersionid());
                List<Map<String, Object>> ctvList = contentTemplDao.selectTemplInfoByTemplVersionId(contVerMap);
                if (CollectionUtils.isEmpty(ctvList)) {
                    // throw new
                    // AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPL_NOT_EXIST,
                    // "未查询到任务内容模板记录！");
                    continue;
                }
                Map<String, Object> outCtvMap = ctvList.get(0);
                totalNum++;

                // task
                Map<String, Object> taskMap = new HashMap<String, Object>();
                taskMap.put("ptTaskId", taskId);
                taskMap.put("seqNo", ptTaskVo.getSeqNo());
                taskMap.put("patientId", patientId);
                taskMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
                taskMap.put("followQueueId", ptTaskVo.getQueueId());
                taskMap.put("quesType", type);
                taskMap.put("templName", outCtvMap.get("templName"));// 问卷名字
                // 随访系统科室id
                taskMap.put("departmentId", followDeptId);
                retList.add(taskMap);
            }
        }
        if (totalNum > 0) {
            retOutMap.put("informMsg", "您有" + totalNum + "份线上随访问卷需要填写，为了医生能够及时掌握您宝宝的健康状态，请前往完成。");
            retOutMap.put("rows", retList);
            retOutMap.put("total", totalNum);
        }

        String queueIdtest = PropertiesUtils.getProperty("queueId");
        String[] arr = queueIdtest.split(",");

        for (String str : arr) {
            if (str.contains(queueIdList.get(0))) {
               retOutMap.put("informMsg", "恭喜宝宝，获得复诊资格！无论出院后面临什么问题，我们都将竭力与您共同应对。为期24个月的院后复诊，对于孩子的成长意义重大，感谢您的配合。");
           }
        }

        return retOutMap;
    }

    // app端获取患者线上随访问卷(查询窗口期内的线上问卷)接口实现
    public HashMap<String, Object> getPtInformOnlineContData(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String patientId = (String) argMap.get("patientId");
        String queueId = (String) argMap.get("queueId");
        String type = (String) argMap.get("type");
        String ptSchemeId = (String) argMap.get("ptSchemeId");
        String taskId = (String) argMap.get("ptTaskId");
        int seqNo = Integer.parseInt((String) argMap.get("seqNo"));

        // 校验患者信息是否存在
        Map<String, Object> userInMap = new HashMap<String, Object>();
        userInMap.put("userId", patientId);
        userInMap.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userInMap);
        if (null == ptVo || StringUtils.isEmpty(ptVo.getId())) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "随访系统无此患者信息！");
        }

        HashMap<String, Object> taskInMap = new HashMap<String, Object>();
        taskInMap.put("taskId", taskId);
        // taskInMap.put("contTemplType", type);// 问卷模板类型
        List<Object> conDataList = new ArrayList<Object>();
        List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
        if (!CollectionUtils.isEmpty(ptcList)) {
            // questiones
            int ipt = 0;
            int isize = ptcList.size();
            Map<String, Object> dataOut = new HashMap<String, Object>();
            Map<String, Object> contVerMap = new HashMap<String, Object>();
            for (ipt = 0; ipt < isize; ipt++) {
                PatientTaskContent ptaskc = ptcList.get(ipt);

                // 获取内容模板
                contVerMap.clear();
                contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
                dataOut = patientSerivce.getContTemplData(contVerMap);
                if (null != dataOut.get("contData")) {
                    conDataList.add(dataOut.get("contData"));
                }
            }
            retOutMap.put("questiones", conDataList);
        }

        // task
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("ptTaskId", taskId);
        taskMap.put("seqNo", seqNo);
        taskMap.put("type", type);
        retOutMap.put("taskInfo", taskMap);

        // ptQueue
        HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
        oprInfoMap.put("patientId", patientId);
        oprInfoMap.put("ptSchemeId", ptSchemeId);
        oprInfoMap.put("followQueueId", queueId);
        retOutMap.put("ptQueueInfo", oprInfoMap);

        return retOutMap;
    }

    // app端获取主诉（登记）任务内容操作详情接口实现
    public HashMap<String, Object> getPtOnlineOperateDetail(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String patientId = (String) argMap.get("patientId");
        String queueId = (String) argMap.get("queueId");
        String type = (String) argMap.get("type");
        String taskId = (String) argMap.get("taskId");
        String updateAccept = (String) argMap.get("updateAccept");
        String appTenantId = (String) argMap.get("appTenantId");

        // 校验患者信息是否存在
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", patientId);
        userMapIn.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userMapIn);
        if (null == ptVo || "".equals(ptVo.getId())) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
        }

        HashMap<String, Object> quMap = new HashMap<String, Object>();
        quMap.put("userId", patientId);
        quMap.put("queueId", queueId);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(quMap);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "队列实例表中无此患者信息！");
        }
        PatientQueueScheme psVo = pqsList.get(0);
        String userStatus = psVo.getUserStatus();
        if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL,
                    "患者在该队列中状态异常，无法进行相关操作！");
        }

        HashMap<String, Object> taskInMap = new HashMap<String, Object>();
        taskInMap.clear();
        taskInMap.put("taskId", taskId);
        List<PatientTask> ptTaskList = patientTaskDao.selectById(taskInMap);
        if (CollectionUtils.isEmpty(ptTaskList)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST,
                    "根据任务id未查询到任务记录，无法进行相关操作！");
        }
        Map<String, Object> valuesMap = new HashMap<String, Object>();
        PatientTask ptTaskVo = ptTaskList.get(0);
        taskInMap.put("contTemplType", type);// 问卷模板类型
        List<Object> conDataList = new ArrayList<Object>();
        List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
        if (!CollectionUtils.isEmpty(ptcList)) {
            // questiones
            int ipt = 0;
            int isize = ptcList.size();
            Map<String, Object> dataOut = new HashMap<String, Object>();
            Map<String, Object> contVerMap = new HashMap<String, Object>();
            for (ipt = 0; ipt < isize; ipt++) {
                PatientTaskContent ptaskc = ptcList.get(ipt);
                // 获取内容模板
                contVerMap.clear();
                contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
                dataOut = patientSerivce.getContTemplData(contVerMap);
                if (null != dataOut.get("contData")) {
                    conDataList.add(dataOut.get("contData"));
                }
            }
            retOutMap.put("questiones", conDataList);

            // values:上次填写的答案，这里从pt_contentdata_info_his表中获取对应那次的记录
            Map<String, Object> valMapIn = new HashMap<String, Object>();
            valMapIn.put("taskId", taskId);
            valMapIn.put("contDataTemplType", type);
            valMapIn.put("updateAccept", updateAccept);
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectCntDataHisByTaskIdAndAccept(valMapIn);
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                int k = 0;
                for (; k < ptTaskConList.size(); k++) {
                    PatientContentData pcdVo = ptTaskConList.get(k);
                    valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                }
            } else if (StringUtils.isNotBlank(appTenantId) && Constants.TENANT_ID_FOR_AYD_MAS.equals(appTenantId)) {
                // 安医大特殊处理，查询不到线上记录，则查询门诊记录
                valMapIn.put("taskId", taskId);
                valMapIn.put("contDataTemplType", Constants.TASK_TYPE_SCHEME_SCHEDULE);
                valMapIn.put("updateAccept", updateAccept);
                ptTaskConList = patientTaskConDao.selectCntDataHisByTaskIdAndAccept(valMapIn);
                if (!CollectionUtils.isEmpty(ptTaskConList)) {
                    int k = 0;
                    for (; k < ptTaskConList.size(); k++) {
                        PatientContentData pcdVo = ptTaskConList.get(k);
                        valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                    }
                }
            }
            retOutMap.put("values", valuesMap);
        }

        // task
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("ptTaskId", taskId);
        taskMap.put("ptTaskName", ptTaskVo.getTaskName());
        taskMap.put("seqNo", ptTaskVo.getSeqNo());
        taskMap.put("type", type);
        // 安医大app端体检报告优化，增加参数 2017.12.22
        String finishDate = ptTaskVo.getFinishDate();
        if (StringUtils.isBlank(finishDate)) {
            String finishTime = ptTaskVo.getFinishTime();
            if (StringUtils.isNotBlank(finishTime)) {
                finishDate = DateUtil.getTimeStampDay(finishTime);
            }
            if (StringUtils.isBlank(finishDate)) {
                String updateTime = ptTaskVo.getUpdateTime();
                finishDate = DateUtil.getTimeStampDay(updateTime);
            }
        }
        String checkAge = ToolUtils.getAgeMonDayByDate3(ptVo.getBirthday(), finishDate);
        if (StringUtils.isBlank(checkAge)) {
            checkAge = "-";
        }
        taskMap.put("finishDate", finishDate);
        taskMap.put("checkAge", checkAge);
        taskMap.put("checkNote", ptTaskVo.getTaskNote());
        retOutMap.put("taskInfo", taskMap);

        // checkIndex
        List<Map<String, Object>> indexList = new ArrayList<Map<String, Object>>();
        if (MapUtils.isNotEmpty(valuesMap)) {
            Map<String, Object> dealMapIn = new HashMap<String, Object>();
            // 查询指导意见
            String guidanceStr = "";
            Map<String, Object> guidanceMapIn = new HashMap<String, Object>();
            guidanceMapIn.put("type", Constants.ASSESSMENT_POSITION_TYPE_FOR_PHYSICAL);
            guidanceMapIn.put("key", Constants.ASSESSMENT_POSITION_KEY_FOR_PHYSICAL_GUIDANCE);
            FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(guidanceMapIn);
            if (null != position) {
                guidanceStr = position.getValue();
            }
            Map<String, Object> guidance = null;
            if (StringUtils.isNotBlank(guidanceStr)) {
                guidance = com.alibaba.fastjson.JSON.parseObject(guidanceStr);
                dealMapIn.put("guidance", guidance);
            }

            Map<String, Object> systolicMapOut = null;// 收缩压6
            Map<String, Object> diastolicMapOut = null;// 舒张压5
            dealMapIn.put("birthday", ptVo.getBirthday());
            dealMapIn.put("finishDate", finishDate);
            dealMapIn.put("pregnancyDay", ptVo.getPregnancyDay());
            dealMapIn.put("gender", ptVo.getGender());
            dealMapIn.put("valuesInfo", valuesMap);
            Iterator<String> iter = valuesMap.keySet().iterator();
            while (iter.hasNext()) {
                Map<String, Object> checkIndexMap = new HashMap<String, Object>();
                String keyId = iter.next();
                dealMapIn.put("quesId", keyId);
                dealMapIn.put("value", valuesMap.get(keyId));
                checkIndexMap = this.getPhysicalInfo(dealMapIn);
                if (MapUtils.isNotEmpty(checkIndexMap)) {
                    Integer assType = (Integer) checkIndexMap.get("type");
                    if (5 == assType) {
                        diastolicMapOut = checkIndexMap;
                    } else if (6 == assType) {
                        systolicMapOut = checkIndexMap;
                    }
                    indexList.add(checkIndexMap);
                }
            }
            // 血压值指标
            char[] bp = { '0', '0' };
            if (MapUtils.isNotEmpty(systolicMapOut)) {
                Integer indexFlag = (Integer) systolicMapOut.get("indexFlag");
                if (null != indexFlag) {
                    if (1 == indexFlag) {
                        bp[0] = '+';
                    } else if (-1 == indexFlag) {
                        bp[0] = '-';
                    }
                }
            }
            if (MapUtils.isNotEmpty(diastolicMapOut)) {
                Integer indexFlag = (Integer) diastolicMapOut.get("indexFlag");
                if (null != indexFlag) {
                    if (1 == indexFlag) {
                        bp[1] = '+';
                    } else if (-1 == indexFlag) {
                        bp[1] = '-';
                    }
                }
            }
            String keyStr = "";
            String bpStr = new String(bp);
            if ("++".equals(bpStr) || "+0".equals(bpStr) || "0+".equals(bpStr)) {
                // 偏高
                keyStr = "max";
            } else if ("--".equals(bpStr) || "-0".equals(bpStr) || "0-".equals(bpStr)) {
                // 偏低
                keyStr = "min";
            } else if ("+-".equals(bpStr)) {
                // 高压偏高，低压偏低
                keyStr = "maxmin";
            } else if ("-+".equals(bpStr)) {
                // 高压偏低，低压偏高
                keyStr = "minmax";
            }
            if (StringUtils.isNotBlank(keyStr) && MapUtils.isNotEmpty(guidance)) {
                // 指导意见（血压需要合并）
                Map<String, Object> typeGui = ToolUtils.typeCast(guidance.get("" + 6));
                if (MapUtils.isNotEmpty(typeGui)) {
                    String guiStr = (String) typeGui.get(keyStr);
                    if (StringUtils.isNotBlank(guiStr)) {
                        systolicMapOut.put("guidanceContent", guiStr);
                    }
                }
            }
            logger.warn("blood--bp==" + bpStr);
        }
        retOutMap.put("checkIndex", indexList);

        // ptQueue
        HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
        oprInfoMap.put("patientId", patientId);
        oprInfoMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
        oprInfoMap.put("followQueueId", queueId);
        retOutMap.put("ptQueueInfo", oprInfoMap);
        return retOutMap;
    }

    // 体检指标
    public Map<String, Object> getPhysicalInfo(Map<String, Object> mapIn) throws Exception {
        Map<String, Object> checkIndexMap = new HashMap<String, Object>();
        String quesId = (String) mapIn.get("quesId");
        String value = (String) mapIn.get("value");
        String finishDate = (String) mapIn.get("finishDate");
        Map<String, Object> valuesInfo = ToolUtils.typeCast(mapIn.get("valuesInfo"));
        Map<String, Object> guidance = ToolUtils.typeCast(mapIn.get("guidance"));
        List<Object> checkStandardList = new ArrayList<Object>();

        checkIndexMap.put("checkId", quesId);
        checkIndexMap.put("checkStandard", checkStandardList);
        checkIndexMap.put("indexFlag", 0);
        checkIndexMap.put("checkValue", value);

        if (StringUtils.isNotBlank(quesId)) {
            Map<String, Object> staticMap = new HashMap<String, Object>();
            staticMap.put("type", Constants.ASSESSMENT_QUESTION_ID_CHECK_TYPE);
            staticMap.put("paramName", quesId);
            List<Map<String, Object>> staticList = confCacheDao.selectBsStaticParamByTenant(staticMap);
            if (!CollectionUtils.isEmpty(staticList)) {
                Map<String, Object> staticOut = staticList.get(0);
                String paramValue = (String) staticOut.get("PARAM_VALUE");
                Integer type = Integer.parseInt(paramValue);
                Map<String, Object> qryMapIn = new HashMap<String, Object>();
                qryMapIn.put("type", type);
                qryMapIn.put("birthday", mapIn.get("birthday"));
                qryMapIn.put("pregnancyDay", mapIn.get("pregnancyDay"));
                qryMapIn.put("finishDate", finishDate);
                String monthKey = ToolUtils.getMonthAgeByBirthAndType(qryMapIn);
                checkIndexMap.put("monthKey", monthKey);
                checkIndexMap.put("type", type);

                // 体脂肪、骨骼肌：获取who2013体重理想数据
                qryMapIn.clear();
                if ((13 == type || 11 == type) && StringUtils.isNotBlank(monthKey)) {
                    Map<String, Object> whoMap = new HashMap<String, Object>();
                    int iage = Integer.parseInt(monthKey);
                    if (iage > 5 * Constants.YEAR_DAY) {
                        whoMap.put("ageMonth", (int) iage / Constants.MONTH_DAY);
                        whoMap.put("standardId", Constants.WHO_STANDARD_ID_FIVEYEAR);
                    } else {
                        whoMap.put("age", iage);
                        whoMap.put("standardId", Constants.WHO_STANDARD_ID);
                    }
                    whoMap.put("gender", mapIn.get("gender"));
                    whoMap.put("length", 0);
                    whoMap.put("standardType", Constants.WHO_STANDARD_TYPE_PERCENT);
                    whoMap.put("developProjectId", Constants.DEVELOPPROJECT_WEIGHT);
                    List<Map<String, Object>> whoMaplist = familyReportDao.selectDevelopStandardForWho(whoMap);
                    if (!CollectionUtils.isEmpty(whoMaplist)) {
                        Map<String, Object> whoMapOut = whoMaplist.get(0);
                        qryMapIn.put("weightBalance", whoMapOut.get("SD0"));
                    }
                }

                String assKey = (String) staticOut.get("PARAM_CODE");
                String assType = (String) staticOut.get("extend_value2");
                String othQuesId = (String) staticOut.get("extend_value3");// 关联的问题(腰围需要根据身高计算)
                String textFlag = (String) staticOut.get("extend_value1");
                if (null == textFlag) {
                    textFlag = "";
                }
                String templData = "";
                if ("1".equals(textFlag)) {
                    // 查询标准指标的json模板
                    Map<String, Object> paramMap = new HashMap<String, Object>();
                    paramMap.put("type", assType);
                    paramMap.put("key", assKey);
                    FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
                    if (null != position) {
                        templData = position.getValue();
                    }
                    if (StringUtils.isBlank(templData)) {
                        return checkIndexMap;
                    }
                }

                if (StringUtils.isNotBlank(othQuesId)) {
                    String extendValue = (String) valuesInfo.get(othQuesId);
                    if (StringUtils.isNotBlank(extendValue)) {
                        qryMapIn.put("extendValue", extendValue);
                    }
                }
                if (StringUtils.isNotBlank(templData)) {
                    qryMapIn.put("templData", templData);
                }
                qryMapIn.put("type", type);
                qryMapIn.put("value", value);
                qryMapIn.put("key", monthKey);
                qryMapIn.put("gender", mapIn.get("gender"));
                Map<String, Object> checkOut = ToolUtils.getPsyChkData(qryMapIn);
                if (MapUtils.isNotEmpty(checkOut)) {
                    Integer indexFlag = (Integer) checkOut.get("indexFlag");
                    List<Object> checkStandardListOut = ToolUtils.typeCast(checkOut.get("checkStandard"));
                    checkIndexMap.put("checkStandard", checkOut.get("checkStandard"));
                    checkIndexMap.put("indexFlag", indexFlag);
                    if (MapUtils.isNotEmpty(guidance) && !(5 == type || 6 == type)) {
                        // 指导意见（血压需要合并）
                        Map<String, Object> typeGui = ToolUtils.typeCast(guidance.get("" + type));
                        if (MapUtils.isNotEmpty(typeGui)) {
                            String guiStr = "";
                            if (-1 == indexFlag) {
                                // 偏低
                                guiStr = (String) typeGui.get("min");
                            } else if (1 == indexFlag) {
                                // 偏高
                                guiStr = (String) typeGui.get("max");
                            } else if (0 == indexFlag && !CollectionUtils.isEmpty(checkStandardListOut)) {
                                // 中等（上臂围）
                                guiStr = (String) typeGui.get("mid");
                            }
                            if (StringUtils.isNotBlank(guiStr)) {
                                checkIndexMap.put("guidanceContent", guiStr);
                            }
                        }
                    }
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

        return checkIndexMap;
    }

    // 更新app激活状态等
    public Map<String, Object> updatePtAppActStatus(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String userId = (String) argMap.get("userId");
        String appActFlag = (String) argMap.get("appActFlag");
        String updateTime = (String) argMap.get("updateTime");
        String updateAccept = (String) argMap.get("updateAccept");

        // 校验患者信息是否存在
        Map<String, Object> userInMap = new HashMap<String, Object>();
        userInMap.put("userId", userId);
        userInMap.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
        Patient ptVo = patientDao.selectById(userInMap);
        if (null == ptVo || StringUtils.isEmpty(ptVo.getId())) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "随访系统无此患者信息！");
        }

        // 更新患者app激活状态
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", userId);
        userMapIn.put("updateTime", updateTime);
        userMapIn.put("appActFlag", appActFlag);
        patientDao.updatePatientInfoById(userMapIn);
        // 历史表记录
        Map<String, Object> userHisMap = new HashMap<String, Object>();
        userHisMap.put("userId", userId);
        userHisMap.put("updateTime", updateTime);
        userHisMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        userHisMap.put("updateAccept", updateAccept);
        patientDao.savePatientHisInfo(userHisMap);

        return retOutMap;
    }

}
